package com.sam.chat.controller;

import com.alibaba.fastjson.JSONObject;
import com.sam.chat.api.CommonResult;
import com.sam.chat.netty.NettyHelper;
import com.sam.chat.netty.ReceiveBean;
import com.sam.chat.service.IChatFriendService;
import com.sam.chat.service.IChatGroupService;
import com.sam.chat.utils.DateUtils;
import com.sam.chat.utils.RedisKeyUtils;
import com.sam.chat.utils.RedisUtils;
import com.sam.chat.vo.FriendVo;
import com.sam.chat.vo.GroupVo;
import com.sam.chat.vo.RoomVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static com.sam.chat.constants.ChatConstant.*;

/**
 * <p>
 * 好友管理
 * </p>
 *
 * @author sam
 * @since 2023-01-07
 */
@Tag(name = "好友管理")
@Log4j2
@RestController
@RequestMapping("/chatFriend")
@RequiredArgsConstructor
@Component
public class ChatFriendController {
    private final IChatFriendService iChatFriendService;
    private final IChatGroupService iChatGroupService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private NettyHelper nettyHelper;

    /**
     * 添加好友
     */
    @Operation(summary = "添加好友")
    @PostMapping("addFriend")
    public CommonResult<Boolean> addFriend(String userId, String friendId) {
        boolean isNew = iChatFriendService.checkFriendId(userId, friendId);
        if (isNew) {
            boolean isSuccess = iChatFriendService.addFriend2(userId, friendId);
            System.out.println("isSuccess" + isSuccess);
            if (isSuccess) {
                ReceiveBean receiveBean1 = new ReceiveBean(friendId, userId, CHAT_TEXT, SINGLE_CHAT, "hello,加好友成功，我们可以开始聊天了",
                        DateUtils.getCurrentDateTime(), UUID.randomUUID().toString(),
                        RedisKeyUtils.getRoomId(userId, friendId), "", "", "");
                String a = JSONObject.toJSONString(receiveBean1);

                ReceiveBean receiveBean2 = new ReceiveBean(userId, friendId, CHAT_TEXT, SINGLE_CHAT, "hello,加好友成功，我们可以开始聊天了",
                        DateUtils.getCurrentDateTime(), UUID.randomUUID().toString(),
                        RedisKeyUtils.getRoomId(userId, friendId), "", "", "");
                String b = JSONObject.toJSONString(receiveBean2);
                readOrUnread(receiveBean1);
                readOrUnread(receiveBean2);

                nettyHelper.pushToUser(userId, a);
                nettyHelper.pushToUser(friendId, b);

            }
            return new CommonResult<>(200, "", isSuccess);
        } else {
            return new CommonResult<>(201, "好友已存在", false);
        }
    }

    /**
     * 删除好友
     */
    @Operation(summary = "删除好友")
    @PostMapping("deleteFriend")
    public CommonResult<Boolean> deleteFriend(String userId, String friendId) {
        boolean isSuccess = iChatFriendService.deleteFriend(userId, friendId);
        return new CommonResult<>(200, "", isSuccess);
    }


    /**
     * 获取我的好友列表
     */
    @Operation(summary = "获取通讯录列表")
    @GetMapping("/getFriendsList")
    public CommonResult<List<FriendVo>> getFriendsList(String uid) {
        List<FriendVo> friendList = iChatFriendService.getFriendsList(uid);
        log.info(friendList);
        return new CommonResult<>(200, "success", friendList);
    }

    /**
     * 获取聊天列表
     */
    @Operation(summary = "App首页获取聊天列表")
    @GetMapping("/getRoomList")
    public CommonResult<List<RoomVo>> getRoomList(String uid) {

        ArrayList<RoomVo> roomList = new ArrayList<>();

        //获取单聊的列表
        Map<Object, Object> singleRoomMap = redisUtils.getHashMap(RedisKeyUtils.getRedisSingleRoomListKey(uid));
        ArrayList<Object> valueList = new ArrayList<>(singleRoomMap.values());//内容
        ArrayList<Object> keyList = new ArrayList<>(singleRoomMap.keySet());//roomId列表
        if (!keyList.isEmpty()) {
            //单聊 ==>  通过roomId 找到用户  userId - toUserId
            for (int i = 0; i < keyList.size(); i++) {
                String chatId = keyList.get(i).toString();
                String[] a = chatId.split("&");
                String toId = "";
                if (uid.equals(a[0])) {
                    toId = a[1];
                } else {
                    toId = a[0];
                }
                FriendVo friendVo = iChatFriendService.getFriendInfo(uid, toId);
                if (friendVo!=null){
                    RoomVo roomSingle = new RoomVo();
                    roomSingle.setRoomId(keyList.get(i).toString());
                    roomSingle.setRoomType(0);//0-单聊 1-群聊
                    roomSingle.setMessageBean(valueList.get(i));
                    roomSingle.setFriendId(toId);
                    roomSingle.setFriendHeader(friendVo.getFriendHeader());
                    roomSingle.setFriendNickName(friendVo.getFriendNickName());
                    roomSingle.setFriendType(friendVo.getType());
                    if (redisUtils.getHashMap(RedisKeyUtils.getRedisUnReadKey(keyList.get(i).toString(), uid)).isEmpty()) {
                        roomSingle.setRead(true);
                    } else {
                        roomSingle.setRead(false);
                    }
                    roomList.add(roomSingle);
                }
            }
        }


        //获取群聊的列表
        Map<Object, Object> groupRoomMap = redisUtils.getHashMap(RedisKeyUtils.getRedisGroupRoomListKey(uid));
        ArrayList<Object> groupMessageIds = new ArrayList<>(groupRoomMap.values());//messageId列表
        ArrayList<Object> groupRoomIds = new ArrayList<>(groupRoomMap.keySet());//roomId列表

        if (!groupRoomIds.isEmpty()) {
            for (int i = 0; i < groupRoomIds.size(); i++) {
                RoomVo roomGroup = new RoomVo();
                GroupVo groupVo = iChatGroupService.getGroupInfo(groupRoomIds.get(i).toString());
                if (groupVo!=null){
                    roomGroup.setRoomId(groupRoomIds.get(i).toString());
                    roomGroup.setRoomType(1);//0-单聊 1-群聊
                    roomGroup.setMessageBean(redisUtils.get(RedisKeyUtils.getGroupInKey(groupMessageIds.get(i) + "")));
                    roomGroup.setGroupName(groupVo.getGroupName());
                    roomGroup.setHeaders(groupVo.getHeaders());
                    roomGroup.setMemberIds(groupVo.getMemberIds());
                    String roomKey = groupRoomIds.get(i).toString();
                    log.info("roomKey" + roomKey);
                    if (redisUtils.getHashMap(RedisKeyUtils.getRedisUnReadKey(roomKey, uid)).isEmpty()) {
                        roomGroup.setRead(true);
                    } else {
                        roomGroup.setRead(false);
                    }
                    roomList.add(roomGroup);
                }
            }
        }
        return new CommonResult<>(200, "success", roomList);

        // return new CommonResult<>(200, "success", new ArrayList<>());
    }

    /**
     * 获取单聊的未读聊天列表
     */
    @Operation(summary = "获取单聊的未读聊天列表")
    @GetMapping("getChatList")
    public CommonResult<List<Object>> getChatList(String chatId, String userId) {
        Map<Object, Object> map = redisUtils.getHashMap(RedisKeyUtils.getRedisUnReadKey(chatId, userId));
        if (map == null) {
            return new CommonResult<>(200, "success", new ArrayList<>());
        }
        List<Object> dataList = new ArrayList<>(map.values());
        return new CommonResult<>(200, "success", dataList);
    }


    /**
     * 获取群聊的未读聊天列表
     */
    @Operation(summary = "获取群聊的未读聊天列表")
    @GetMapping("getGroupChatList")
    public CommonResult<List<Object>> getGroupChatList(String roomId, String userId) {
        Map<Object, Object> map = redisUtils.getHashMap(RedisKeyUtils.getRedisUnReadKey(roomId, userId));
        if (map == null) {
            return new CommonResult<>(200, "success", new ArrayList<>());
        }
        List<Object> dataList = new ArrayList<>();
        for (Object messageId : map.keySet()) {
            dataList.add(redisUtils.get(RedisKeyUtils.getGroupInKey(messageId.toString())));
        }
        return new CommonResult<>(200, "success", dataList);
    }


    /**
     * 判读已读未读的redis逻辑
     */
    private void readOrUnread(ReceiveBean receiveBean) {
        //标记已读未读
        //聊天界面id uid+&+toId uid/toId小的在前面
        try {
            if (null == receiveBean.getRoomId() || receiveBean.getRoomId().isEmpty()) {
                return;
            }
            //有聊天进来，更新
            if (receiveBean.getType() == CHAT_TEXT) {
                //app端首页roomList的插入,更新
                redisUtils.insertHash(
                        RedisKeyUtils.getRedisSingleRoomListKey(receiveBean.getUserId()),
                        receiveBean.getRoomId(),
                        receiveBean);
                redisUtils.insertHash(
                        RedisKeyUtils.getRedisSingleRoomListKey(receiveBean.getToUid()),
                        receiveBean.getRoomId(),
                        receiveBean);
                //标记未读
                redisUtils.insertHash(
                        RedisKeyUtils.getRedisUnReadKey(receiveBean.getRoomId(), receiveBean.getToUid()),
                        receiveBean.getMessageId(),
                        receiveBean);
            }

            if (receiveBean.getType() == 0 && CHAT_READ_ACK.equals(receiveBean.getMessage())) {
                //删除已读
                redisUtils.del(RedisKeyUtils.getRedisUnReadKey(receiveBean.getRoomId(), receiveBean.getUserId()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

